#/bin/sh

clean_added_files() {
	format="$1"
	for i in *.$format.added; do 
		mv -- "$i" "${i%%.added}"
	done
}


process_folder() {
	folder="$1"
	format="$2"
	echo "==========================="
	echo "Processing $folder/"
	echo "==========================="
	cd -- "$folder"
	clean_added_files "$format"
	for file in *.toml; do
		echo
		echo "Processing $file"

		download_mode="$(grep 'mode' < "$file" | cut -d' ' -f3)"
		# remove double quotes
		download_mode="${download_mode#\"}"
		download_mode="${download_mode%\"}"

		filename="$(grep 'filename' < "$file" | cut -d' ' -f3-)"
		# remove double quotes
		filename="${filename#\"}"
		filename="${filename%\"}"
		filename_url="$(printf '%s' "$filename" | sed 's/ /%20/g')"

		if [ "$download_mode" = 'metadata:curseforge' ]; then
			file_id="$(grep 'file-id' < "$file" | cut -d' ' -f3)"
			# remove double quotes
			file_id="${file_id#\"}"
			file_id="${file_id%\"}"

			url="https://edge.forgecdn.net/files/$(printf '%s' "$file_id" | cut -c1-4)/$(printf '%s' "$file_id" | cut -c5-7)/$filename_url"
		else
			url="$(grep 'url' < "$file" | cut -d' ' -f3)"
			# remove double quotes
			url="${url#\"}"
			url="${url%\"}"
		fi

		if [ -e "$filename" ]; then
			echo "$filename exists, skipping..."
		else
			echo "$filename from $url"
			curl -L "$url" -o "$filename"
		fi
		mv "$filename" "${filename}.added"
	done

	printf 'Processed %s mod files and %s .pw.toml files\n' "$(ls *.$format.added | wc --lines)" "$(ls *.pw.toml | wc --lines)"
	echo "Unrecognized .$format files:"
	ls *.$format
	clean_added_files "$format"
	cd -
}

process_folder mods/ jar
process_folder resourcepacks/ zip
